package com.canbot.u05.activity.shoppingGuide.sales;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.sales.RouteGuideAdapter;
import com.canbot.u05.bean.sales.RouteGuide;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.SellModePropagandaDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @author lt
 *         路线指引设置
 */
public class RouteActivity extends BaseActivityNoTitle {

        //private List<String> dList;
        private RecyclerView mRecyclerView;

        private RouteGuideAdapter list_ada;

        public int currentPosition;

        private List<RouteGuide> infoList = new ArrayList<>();

        private String resultDelete;

        private static final int TIMEOUT = 100;//超时时间100s

        private static final int HEAD_DEL_DATA_SUCCESS = 501;

        private static final int HEAD_DEL_DATA_FAILURE = 502;

        private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message message) {
                        super.handleMessage(message);
                        switch (message.what) {
                                case 101://加载数据失败
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.network_error));
                                        break;
                                case 102://加载数据成功
                                        list_ada.notifyDataSetChanged();
                                        break;
                                case 201://删除数据失败
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.delete_failed));
                                        break;
                                case 202://删除数据成功
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.deleted_successfully));
                                        list_ada.notifyDataSetChanged();
                                        break;
                                case 301://重命名失败
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.rename_failed));
                                        break;
                                case 302://重命名成功
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.rename_success));
                                        list_ada.notifyDataSetChanged();
                                        break;
                                case HEAD_DEL_DATA_SUCCESS:
//                                        deleteActionChest(actionInfoId);
                                        break;
                                case HEAD_DEL_DATA_FAILURE:
                                        break;
                        }
                }
        };

        private Dialog dialogLoading;

        private String actionInfoId;


        @Override
        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_route);

                mRecyclerView = (RecyclerView) findViewById(R.id.listView);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                list_ada = new RouteGuideAdapter(this, infoList,mRecyclerView);
                mRecyclerView.setAdapter(list_ada);
                DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
                dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.shape_custom_divider));
                mRecyclerView.addItemDecoration(dividerItemDecoration);
                String seekinfo = getIntent().getStringExtra("seekinfo");

                if (TextUtils.isEmpty(seekinfo)) {
                        initData();
                }
                else {
                        //ActionInfo sellInfo = new Gson().fromJson(seekinfo,ActionInfo.class);
                        List<RouteGuide> sellInfo = JSON.parseArray(seekinfo, RouteGuide.class);

                        if (sellInfo != null) {
                /*List<ActionInfo> infoLists = sellInfoList.getInfoList();
                seekinfo*/
                                // infoList.addAll(infoLists);
                                infoList.addAll(sellInfo);
                        }
                        else {
                                initData();
                        }
                }
                list_ada.setListner(new RouteGuideAdapter.AdapterOnclickListner() {
                        @Override
                        public void onclick(int id) {

                                switch (id) {
                                        case R.id.btn_1://修改信息地址
                                                RouteGuide routeInfo = infoList.get(currentPosition);
                                                // int id1 = routeInfo.getId();
                                                String id1 = routeInfo.getId();

                                                String address = routeInfo.getAddress();
                                                String title = routeInfo.getTitle();
                                                String pic = routeInfo.getPic();

                                                ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.modify_information_address));

                                                Intent intent = new Intent(RouteActivity.this, AddRouteActivity.class);
                                                intent.putExtra("edit", "address");
                                                intent.putExtra("id", id1 + "");
                                                intent.putExtra("title", title);
                                                intent.putExtra("address", address);
                                                intent.putExtra("pic", pic);

                                                startActivity(intent);
                                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                                break;
                                        case R.id.btn_name://修改回答语音
                                                RouteGuide routeInf = infoList.get(currentPosition);
                                                //int id2 = routeInf.getId();
                                                String id2 = routeInf.getId();
                                                String voice = routeInf.getVoice();
                                                int type = routeInf.getType();

                                                ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.modify_response));
                                                Intent intent2 = new Intent(RouteActivity.this, SpeechSetupActivity.class);
                                                intent2.putExtra("edit", "speech");
                                                intent2.putExtra("id", id2);
                                                intent2.putExtra("voice", voice);
                                                intent2.putExtra("type", type);

                                                startActivity(intent2);
                                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                                break;
                                        case R.id.btn_delet://删除数据
                                                showTaskDialog(id);
                                                break;
                                        default:
                                                break;
                                }
                        }

                        @Override
                        public void showPopuwindow(int position) {
                                currentPosition = position;
                        }

                        @Override
                        public void doTask() {
                                ToastTools.newInstance(RouteActivity.this).showText("doTask:" + currentPosition);
                        }
                });

        }

        private void initData() {

                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<List<RouteGuide>> queryAll = salesApi.getAllRoute("queryAll");

                queryAll.enqueue(new Callback<List<RouteGuide>>() {
                        @Override
                        public void onResponse(Call<List<RouteGuide>> call, Response<List<RouteGuide>> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        Log.d("ActionSeekActivity", "所有路线信息·" + response.body().toString());
                                        List<RouteGuide> infos = response.body();
                                        infoList.clear();
                                        infoList.addAll(infos);
                                        list_ada.notifyDataSetChanged();
                                        message.what = 102;
                                        handler.sendMessage(message);
                                }
                                else {
                                        message.what = 101;
                                        handler.sendMessage(message);
                                }
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }

                        @Override
                        public void onFailure(Call<List<RouteGuide>> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }
                });


//                for (int i = 0; i < 21; i++) {
//                        RouteGuide routeGuide = new RouteGuide();
//                        routeGuide.setId(i);
//                        routeGuide.setTitle("肯德基" + i);
//                        routeGuide.setAddress("朗山路206号同方信息港一楼 朗山路206号同方信息港一楼");
//                        routeGuide.setPic("");
//                        routeGuide.setVoice("");
//                        routeGuide.setType(1);
//                        infoList.add(routeGuide);
//                }
//                list_ada.notifyDataSetChanged();


        }

        //添加任务对话框
        public void showTaskDialog(int id) {
                final SellModePropagandaDialog dialog = new SellModePropagandaDialog(this, id);
                dialog.setListner(new SellModePropagandaDialog.ModeDialogOclickListner() {
                        @Override
                        public void onClick(int id) {
                                switch (id) {

                                        case R.id.btn_delet://删除
                                                dialog.show();
                                                break;
                                        case R.id.btn_rename_normal://换名

                                                break;

                                        //重命名的取消
                                        case R.id.btn_dialog_del_left:
                                                dialog.dismiss();
                                                break;
                                        //删除的确认
                                        case R.id.btn_dialog_del_right:
                                                Log.d("SalesSettingsActivity", "删除数据的fffid" + id);
                                                RouteGuide actionInfo = infoList.get(currentPosition);
                                                dialog.dismiss();
                                                // int actionInfoId = actionInfo.getId();
                                                actionInfoId = actionInfo.getId();
                                                deleteActionChest(actionInfoId);

                                                break;
                                        //重命名的取消
                                        case R.id.btn_dialogleft:
                                                dialog.dismiss();
                                                break;
                                        //重命名的确认
                                        case R.id.btn_dialogright:
                                                dialog.dismiss();
                                                break;

                                }
                        }
                });
                dialog.show();
                setDialogWindowAttr(dialog, this);
        }


        //设置对话框显示
        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x590);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x340);
                dlg.getWindow().setAttributes(lp);
        }

        //添加键
        public void add(View view) {
                String s = JSON.toJSONString(infoList);

                        Intent intent = new Intent(this, AddRouteActivity.class);
                        intent.putExtra("info", s);
                        startActivity(intent);
                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);

        }

        /**
         * //返回键
         *
         * @param view
         */
        public void delete(View view) {
//        if (infoList.size()==0) {
//            MsgSendUtils.sendStringMsg(MsgType.SEND_MSG_STATE,2+"");
//            startActivity(new Intent(SalesSettingsActivity.this,SalesPersonalityActivity.class));
//            overridePendingTransition(R.anim.face_zoom_enter,
//                    R.anim.face_zoom_exit);
//        }else {
//            MsgSendUtils.sendStringMsg(MsgType.SEND_MSG_STATE,1+"");
//            startActivity(new Intent(SalesSettingsActivity.this,SalesBannerActivity.class));
//            overridePendingTransition(R.anim.face_zoom_enter,
//                    R.anim.face_zoom_exit);
//        }
                //startActivity(new Intent(this,ShoppingGuideSettingActivity.class));
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }



        public void deleteActionChest(final String id) {
                Log.d("SalesSettingsActivity", "删除数据的id" + id);
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.delete));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.delRouteInfo(id + "");
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                if ("0".equals(response.body())) {
//                                        handler.sendEmptyMessage(HEAD_DEL_DATA_SUCCESS);
                                        for (int i = 0; i < infoList.size(); i++) {
                                                RouteGuide sellInfo = infoList.get(i);
                                                //int sellid = sellInfo.getId();
                                                String sellid = sellInfo.getId();
                                                if (sellid.equals(id)) {
                                                        infoList.remove(i);
                                                        break;
                                                }
                                        }
                                        Log.d("SalesSettingsActivity", "删除数据返回值" + response.body());
                                        String result = response.body();
                                        resultDelete = result;
                                        ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.deleted_successfully));

                                        list_ada.notifyDataSetChanged();

                                }
                                else {
                                        handler.sendEmptyMessage(HEAD_DEL_DATA_FAILURE);
                                }


                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(RouteActivity.this).showText(getString(R.string.delete_failed));
                        }
                });

        }


        @Override
        protected void onResume() {
                super.onResume();
//        MsgSendUtils.sendStringMsg(MsgType.SEND_MSG_STATE,"0");
                //MsgSendUtils.sendStringMsg(MsgType.SEND_PAD_ENTER_ROUTE_SETUP,"enter route");


        }

        @Override
        protected void onRestart() {
                super.onRestart();
                initData();
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                if (infoList != null) {
                        infoList.clear();
                }
        }

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }
}